/**
 * 
 */
package com.study.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Administrator
 * @date 2019年6月9日
 */

public class ServerBootStrap {
    public static void main(String[] args) throws InterruptedException {
        //1.Create ServerBootstrap
        ServerBootstrap sbt = new ServerBootstrap();
        //2.Create thread pool(boss & worker)
        //2.定义工作组:boss分发请求给各个worker:boss负责监听端口请求，worker负责处理请求（读写）
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        //3.关联线程池(boss负责请求转发，worker负责事件处理)
        sbt.group(boss,worker);
        //4.Set up the server
        sbt.channel(NioServerSocketChannel.class);
        //5.Initialize the communication channel (key point)
        sbt.childHandler(new ServerChannelInitizlizer());
        //6.Bind listening port
        System.out.println("我在@9999端口监听...");
        
        //6.设置参数
        //设置参数，TCP参数
        sbt.option(ChannelOption.SO_BACKLOG, 2048);         //连接缓冲池的大小
        sbt.childOption(ChannelOption.SO_KEEPALIVE, true);//维持链接的活跃，清除死链接
        sbt.childOption(ChannelOption.TCP_NODELAY, true);//关闭延迟发送

        //7.绑定ip和port
        try {
            ChannelFuture channelFuture = sbt.bind(9999).sync();//Future模式的channel对象
            //7.5.监听关闭
            channelFuture.channel().closeFuture().sync();  //等待服务关闭，关闭后应该释放资源
        } catch (InterruptedException e) {
            System.out.println("server start got exception!");
            e.printStackTrace();
        }finally {
            //8.优雅的关闭资源
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
        
    }
}